<template>
    <div style="height:100%;width:100%;">
        <div style="height:100%;width:100%;" ref="MapView"></div>
        <div class="control">
            <div class="ItemControl" @click="changeLayerDefault(item)" v-for="(item,index) in MapOptions" :key="'control_' + index">
                <span>{{ (item.default ? '▶ ' : '') + item.name}}</span>
            </div>
        </div>
    </div>
</template>
<script>
import simpleMap from '@best/libs-cli/simpleMap/index.js'

var map = null;
var mapConfig = [{
    "type": "arcgis",
    "name": "Aicgis",
    "layerType": "background",
    "url": "http://cache1.arcgisonline.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer",
    "default": true
}, {
    "type": "TD",
    "name": "卫星地图",
    "layerType": "background",
    "url": "https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
    "default": false
}, {
    "type": "TD",
    "name": "天地图",
    "layerType": "background",
    "url": "http://192.168.3.81:7001/maps/TDTMap/{z}/{x}/{reverseY}.png",
    "default": false
}, {
    "type": "TD",
    "name": "标注信息",
    "layerType": "mark",
    "url": "http://192.168.3.81:7001/maps/TDTMapMark/{z}/{x}/{reverseY}.png",
    "default": false
}]

export default {
    data() {
        return {
            value: '',
            MapOptions: [],
        }
    },
    mounted() {
        map = simpleMap.initMap(this.$refs.MapView);
        map.addProviders(mapConfig);
        // 因为只能切换 background 类型的图层，故需要手动过滤
        for (let i = 0; i < mapConfig.length; i++) {
            const element = mapConfig[i];
            if (element.layerType == 'background') {
                this.MapOptions.push(element);
            }
        }
    },
    methods: {
        changeLayerDefault(item) {
            if (item.default) return;
            // 注意，此处改变的是原始数据，不是this下绑定的显示数据，防止丢失 mark 图层
            for (let i = 0; i < mapConfig.length; i++) {
                const element = mapConfig[i];
                element.default = false;
            }
            item.default = true;
            // 重新添加图源
            map.addProviders(mapConfig);
        }
    },
    beforeDestroy() {
        // 页面被注销时，销毁地图
        map && map.destroy();
    }
}
</script>
<style scoped>
.control {
    position: absolute;
    top: 20px;
    left: 20px;
    background: rgba(0, 0, 0, 0.4);
    padding: 10px 20px;
}
.ItemControl {
    color: #fff;
    padding: 5px;
    cursor: pointer;
}
</style>